import { useState, useEffect, useRef, useContext } from 'react'
import { Table, Form, Button, Input, Modal, message } from 'antd'
import { configContext, getLocalValue } from '../../../config/env'
import commonService from '../../../service/index'

function BroadcastChannel() {
  const [tableData, setData] = useState<any>([])
  const [categoryData, setCategoryData] = useState<any>([])
  const [loading, setLoading] = useState(true)
  const [param, setParam] = useState({
    id: ''
  })
  const [categoryId, setCategoryId] = useState('')
  const [height, setHeight] = useState(600)
  const [dataItem, setDataItem] = useState<any>({})
  const [showChannelModal, updateChannelModal] = useState(false);
  const [categoryModal, setCategoryModal] = useState(false)
  const tableRef = useRef<any>()
  const localValue = useContext(configContext)

  useEffect(() => {
    getData()
    getCategoryData()
    if (tableRef.current && tableRef.current.offsetHeight) {
      setHeight(tableRef.current.offsetHeight)
    }
  }, [])

  const getData = async () => {
    setData([])
    setLoading(true)
    const data:any = await commonService.getChannelData({})
    setLoading(false)
    if (data) {
      setData(param.id ? data.filter((item: any) => item.channel_id == param.id) : data)
    }
  }
  
  const getParamValue = (e:any, type:string) => {
    setParam({
      ...param,
      [type]: e.target.value
    })
  }

  const getCategoryData = async () => {
    const data:any = await commonService.getBroadcastCategory({
      or: '(type.eq.root,type.eq.channel)'
    })
    if (data) {
      setCategoryData(data)
    }
  }

  const handleUpdateCateory = async () => {
    const data:any = await commonService.updateCategoryData({
      op: 8,
      op_param1: dataItem.channel_id,
      op_param2: dataItem.title
    })
    if (!data.message) {
      message.success('修改频道成功')
      updateChannelModal(false)
      getData()
    } else {
      message.error(data.message)
    }
  }

  const handleAddChannel = async () => {
    if (!categoryId) {
      message.error('请选择分类')
      return
    }
    const data:any = await commonService.updateCategoryData({
      op: 4,
      op_param1: dataItem.id,
      op_param2: categoryId
    })
    if (!data.message) {
      message.success('添加频道至分类成功')
      setCategoryModal(false)
      getData()
    } else {
      message.error(data.message)
    }
  }

  return ( 
     <div className='table-content' ref={tableRef}>
       <div className='title'>{getLocalValue(localValue, '直播频道','Live stream channel')}</div>
       <div className='table'>
        <div className='form'>
        <Form layout='inline'>
          <Form.Item label={getLocalValue(localValue, '频道ID','channel ID')}>
            <Input style={{width: 200}} value={param.id} allowClear onChange={(e) => getParamValue(e, 'id')} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={getData}>{getLocalValue(localValue, '查询','query')}</Button>
          </Form.Item>
        </Form>
        </div>
        <Table loading={loading} dataSource={tableData} pagination={false} scroll={{y: height - 200}} rowKey='channel_id' columns={
          [{
            title: getLocalValue(localValue, '频道ID','category ID'),
            dataIndex: 'channel_id',
            width: 100
          },
          {
            title: getLocalValue(localValue, '国家','country'),
            dataIndex: 'country',
            width: 100
          },
          {
            title: getLocalValue(localValue, '描述','description'),
            dataIndex: 'description',
            width: 90
          },
          {
            title: getLocalValue(localValue, '语言','language'),
            dataIndex: 'language',
            width: 90
          },
          {
            title: getLocalValue(localValue, '标题','title'),
            dataIndex: 'title',
            width: 200
          },
          {
            title: getLocalValue(localValue, '媒体类型','media type'),
            dataIndex: 'media_type',
            width: 130
          },
          {
            title: getLocalValue(localValue, '图标','icon'),
            dataIndex: 'photo_uri',
            width: 190,
          },
          {
            title: 'subtitle',
            dataIndex: 'subtitle',
            width: 100
          },
          {
            title: getLocalValue(localValue, '操作','action field'),
            width: 190,
            render: (row) => {
              return <div>
                <Button type="link" onClick={() => {updateChannelModal(true);setDataItem(row)}}>{getLocalValue(localValue, '修改','update')}</Button>
                <Button type="link" onClick={() => {setCategoryModal(true);setDataItem(row); setCategoryId('')}}>{getLocalValue(localValue, '添加','add')}</Button>
              </div>
            }
          }]
        } ></Table>
       </div>
       
       <Modal title={getLocalValue(localValue, '修改频道名称', 'update channel')} width={600} open={showChannelModal} maskClosable={false}	okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={handleUpdateCateory} onCancel={() => {updateChannelModal(false) }} >
          <Form layout='inline' labelCol={{span: 3}}>
            <Form.Item label={getLocalValue(localValue, '频道名称', 'channel name')} style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} value={dataItem.title} allowClear onChange={(e) => {setDataItem({...dataItem, title: e.target.value})}} />
            </Form.Item>
          </Form>
       </Modal>

       <Modal title={getLocalValue(localValue, '添加至直播分类', 'add to live stream category')} width={900} open={categoryModal} maskClosable={false}	okText={getLocalValue(localValue, '添加', 'add')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={handleAddChannel} onCancel={() => {setCategoryModal(false) }} >
        <Table dataSource={categoryData} pagination={false} scroll={{y: 600}} rowKey='category_id' 
        rowSelection={{
          type: 'radio',
          selectedRowKeys: categoryId ? [categoryId] : [],
          onChange: (id:any) => {
            setCategoryId(id[0])
          },
        }}
        columns={
            [{
              title: getLocalValue(localValue, '分类ID','category ID'),
              dataIndex: 'category_id',
              width: 200
            },
            {
              title: getLocalValue(localValue, 'title','title'),
              dataIndex: 'title',
              width: 130
            },
            {
              title: 'type',
              dataIndex: 'type',
              width: 90
            },
            {
              title: 'path',
              dataIndex: 'path',
              width: 190
            },
            {
              title: getLocalValue(localValue, '图标','icon'),
              dataIndex: 'photo_uri',
              width: 190,
            }]
          } ></Table>
       </Modal>

     </div>
  )
}

export default BroadcastChannel